package com.my.app.base;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Created by 80002023 on 2016/5/4.
 */
public abstract class HibernateSupport<K extends Serializable, V> extends HibernateDaoSupport implements IDao<K, V> {

    private Class<V> clazz;

    public HibernateSupport() {
        // 在父类中查找子类定义的泛型信息
        ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
        clazz = (Class) pt.getActualTypeArguments()[1];
    }

    @Resource
    public void setCurrentFactory(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }

    public V findById(K id) {
        return currentSession().get(clazz, id);
    }

    public List<V> findAll() {
        return currentSession().createQuery("from " + clazz.getName()).list();
    }

    public void create(V entity) {
        currentSession().saveOrUpdate(entity);
    }

    public V update(V entity) {
        currentSession().update(entity);
        return entity;
    }

    public void delete(V entity) {
        currentSession().delete(entity);
    }

    public void deleteById(K entityId) {
        delete(findById(entityId));
    }
}
